<?php

/* returns channel data as type 0 and item tag data as type = 1 */
function RSS_Item($item, $type)
{
	$item_array = array();
	$tnl = $item->getElementsByTagName('title');
	$tnl = $tnl->item(0);
	$title = $tnl->firstChild->textContent;

	$tnl = $item->getElementsByTagName('link');
	$tnl = $tnl->item(0);
	$link = $tnl->firstChild->textContent;
	
	$tnl = $item->getElementsByTagName('pubDate');
	$tnl = $tnl->item(0);
	$pubdate = $tnl->firstChild->textContent;		

	$tnl = $item->getElementsByTagName('description');
	$tnl = $tnl->item(0);
	$description = $tnl->firstChild->textContent;
	
	$tnl = $item->getElementsByTagName('guid');
	$tnl = $tnl->item(0);
	$author = $tnl->firstChild->textContent;
	
	$item_array['title'] = $title;
	$item_array['link'] = $link;
	$item_array['pubdate'] = (!empty($pubdate)) ? $pubdate : NULL;		
	$item_array['description'] = $description;
	$item_array['type'] = $type;
	$item_array['guid'] = $author;

	if($type == 0)
	{
		$tnl = $item->getElementsByTagName('author');
		$tnl = $tnl->item(0);
		$author = $tnl->firstChild->textContent;
		$item_array['author'] = $author;
	}

	return $item_array;
}


/* return channel and items of channel as array */
function RSS_Channel($channel)
{
	$RSS_Content = array();
	$items = $channel->getElementsByTagName('item');
	
	// Processing channel
	// get description , title of channel as type 0
	$channel_meta = RSS_Item($channel, 0);	
	array_push($RSS_Content, $channel_meta);
	
	// Processing articles
	foreach($items as $item)
	{
		// get description , title, ... of channel as type 1
		$item_data = RSS_Item($item, 1);
		array_push($RSS_Content, $item_data);
	}
	
	return $RSS_Content;
}

function RSS_Retrieve($url)
{
	
	$RSS_Channel = array();
	try 
	{
		$doc  = new DOMDocument();
		$doc->load($url);

		$channels = $doc->getElementsByTagName('channel');
		foreach($channels as $channel)
		{
			$RSS_Channel[] = RSS_Channel($channel);
		}
	} 
	catch (Exception $e) 
	{
		echo 'Exception : URL = ', $url, 'Error Message = ' ,$e->getMessage(), "\n";  
		return FALSE;
	}
	return $RSS_Channel;
	
}

?>
